package Client;
import java.io.DataInputStream;
import java.io.IOException;

import javax.swing.JTextArea;

/**
 * SReceiver
 * 
 * Thread for reading socket information
 * @author Yaxing Chen
 *
 */
class ClientReceiver extends Thread{
	private String separator = ">>><<<";
    private DataInputStream dis;
    private JTextArea area;
    private int identify; //0: server, 1: clients
    private int id; //id #
    
    public ClientReceiver(DataInputStream d,JTextArea a, int id, int idNum){
        this.dis = d;
        this.area = a;
        this.identify = id;
        this.id = idNum;
    }
    
    public void run(){
        String input;
        String[] contentTmp;
        String content;
        int sourceClientId;
        while(true){
            try{
            	if(dis == null){
            		break;
            	}
            	input = dis.readUTF();
              
            	contentTmp = input.split(separator);
            	
            	if(contentTmp.length < 2){
            		area.append("Retrieving data error, restart.");
            		break;
            	}
            	
            	sourceClientId = Integer.parseInt(contentTmp[0]);
            	content = contentTmp[1];
            	
                area.append("From client #"+ sourceClientId + " to you(#"+id+") :" + content);
                
                if(content.equals("bye")){
                    dis.close();
                    area.setText("Exit!");
                    break;
                } 
                
            }catch(IOException e){
                e.printStackTrace();
                break;
            }
        }
    }
}